<template>
  <!-- 已登录状态 -->
  <div v-if="logined">
    <div class="order-hall">
    <!-- 顶部导航栏，显示标题 "我的订单" -->
    <van-nav-bar title="我的订单" :border="false" />

    <!-- 搜索栏容器 -->
    <div class="search-container">
      <van-search
        v-model="searchText"
        placeholder="请输入关键字进行搜索"
        shape="round"
        background="#ffffff"
        :style="{ flex: 1 }"
      />
      <van-button size="small" type="primary" class="search-button" @click="onSearch">查询</van-button>
    </div>

    <!-- 筛选按钮容器 -->
    <div class="filter-buttons">
      <!-- <van-button
        plain
        hairline
        type="primary"
        size="small"
        class="filter-button"
        :class="{ active: activeFilter === '全部' }"
        @click="setActiveFilter('全部')"
      >
        全部
      </van-button> -->
      <van-button
        plain
        hairline
        type="primary"
        size="small"
        class="filter-button"
        :class="{ active: activeFilter === '我发布的' }"
        @click="setActiveFilter('我发布的')"
      >
        我发布的
      </van-button>
      <van-button
        plain
        hairline
        type="primary"
        size="small"
        class="filter-button"
        :class="{ active: activeFilter === '我领取的' }"
        @click="setActiveFilter('我领取的')"
      >
        我领取的
      </van-button>
    </div>

    <!-- 订单列表 -->
    <van-list
      v-model:loading="loading"
      :finished="finished"
      finished-text="没有更多了"
      @load="onLoad"
      v-loading="loading"
    >
      <van-cell-group class="orderList" v-for="order in orders" :key="order.orderId" inset @click="showOrderDetail(order)">
        <!-- 订单项：订单信息 -->
        <van-cell>
          <template #icon>
            <!-- 头像 -->
            <img :src="order.avatar || defaultAvatar" style="width: 40px;height: 40px;border-radius: 50%;">
          </template>
          <template #value>
            <!-- 订单详情 -->
            <span class="order-info">{{ '订单号: ' + order.orderId }}</span>
          </template>
          <template #right-icon>
            <span v-if="order.orderStatus===0" class="status-ongoing">
              <span class="status-dot"></span>
              空闲中
            </span>
            <span v-else-if="order.orderStatus===1" class="status-completed">
              <span class="status-dot"></span>
              进行中
            </span>
            <span v-else-if="order.orderStatus === 3" class="status-pending">
              <span class="status-dot"></span>
              待确认
            </span>
            <span v-else-if="order.orderStatus === 2" class="status-done">
              <span class="status-dot"></span>
              已完成
            </span>
          </template>
        </van-cell>
        <!-- 订单项：取件地址信息 -->
        <van-cell>
          <template #icon>
            <!-- 取件图标 -->
            <img src="../../assets/images/pickuplogo.png" class="logoStyle">
          </template>
          <template #value>
            <!-- 地址详情 -->
            <span class="addressStyle">{{ order.pickupAddress }}</span>
          </template>
          <template #right-icon>
            <van-tag size="large" v-if="activeFilter==='我发布的'" plain class="yellow-tag">发</van-tag>
            <van-tag size="large" v-else plain class="green-tag">取</van-tag>
          </template>
        </van-cell>
        <!-- 订单项：收件地址信息 -->
        <van-cell>
          <template #icon>
            <!-- 收件图标 -->
            <img src="../../assets/images/deliverylogo.png" class="logoStyle">
          </template>
          <template #value>
            <!-- 地址描述 -->
            <span class="addressStyle">{{ order.deliveryAddress }}</span>
          </template>
          <template #right-icon>
            <div class="task-price">
              <!-- 价格信息 -->
              <span class="price">{{ order.reward }}元</span>
              <!-- 订单时间信息 -->
              <div class="order-info">
                <span style="margin-right: 15px;">{{ order.timeAgo}}</span>
              </div>
            </div>
          </template>
        </van-cell>
      </van-cell-group>
    </van-list>
    </div>
  </div>
  <!-- 未登录状态 -->
  <div  class="unlogin" v-else>
      <img src="../../assets/images/未登录-头像.png" alt="">
      <h3>暂未登录</h3>
      <div class="des">快去登录，迫不及待与你相见啦~</div>
      <button @click="gotologin">立即登录</button>
  </div>

  <div v-if="showDialog" class="dialog-wrapper">
    <div class="dialog-background" @click="showDialog = false"></div>
    <div :class="['content-background', { 'content-background-large': selectedTask?.orderStatus === 2 }]">
      <h3>订单详情</h3>
      <img src="../../assets/images/OrderDetailback.png" alt="" class="back-person">
      <div :class="['dialog-content', { 'dialog-content-large': selectedTask?.orderStatus === 2 }]">
        <div class="order-detail">
          <div class="detail-item">
            <div class="orange">
              <div class="label">取件地址：</div>
            </div>
            <span class="value">{{ selectedTask.pickupAddress }}</span>
          </div>
          <div class="detail-item">
            <div class="orange">
              <div class="label">收件地址：</div>
            </div>
            <span class="value">{{ selectedTask.deliveryAddress }}</span>
          </div>
          <div class="detail-item">
            <div class="orange">
              <div class="label">联系方式：</div>
            </div>
            <span class="value">{{ selectedTask.phoneNumber }}</span>
          </div>
          <div class="detail-item">
            <div class="orange">
              <div class="label">快递信息：</div>
            </div>
            <span class="value">
              <template v-if="selectedTask.smallNum > 0">{{ selectedTask.smallNum }} 件小件</template>
              <template v-if="selectedTask.mediumNum > 0">{{ selectedTask.mediumNum }} 件中件</template>
              <template v-if="selectedTask.bigNum > 0">{{ selectedTask.bigNum }} 件大件</template>
            </span>
          </div>
          <div class="detail-item">
            <div class="orange">
              <div class="label">备注信息：</div>
            </div>
            <span class="value">{{ selectedTask.description }}</span>
          </div>
          <div class="detail-item">
            <div class="orange-qu">
              <div class="label">取件码：</div>
            </div>
            <span class="value">{{ selectedTask.code }}</span>
          </div>
          <div v-if="selectedTask?.orderStatus === 0" class="cancel-btn">
            <button @click="cancelOrder1">取消订单</button>
          </div>
          <div v-else-if="selectedTask.orderStatus === 1" class="orderisdoing">
            <div v-if="activeFilter === '我发布的'" class="doing-span">
              <span>订单正在进行</span>  
            </div>
            <div v-else class="doing-btn">
              <button @click="abandonOrder" class="btn1">放弃订单</button>
              <button @click="finishOrder" class="btn2">完成订单</button>
            </div>
          </div>
          <div v-else-if="selectedTask.orderStatus === 3" class="confirm-btn">
            <div v-if="activeFilter === '我领取的'" class="confirm-span">
              <span>等待对方确认</span>
            </div>
            <div v-else>
              <button @click="confirmCompletion">确认完成</button>  
            </div>
          </div>
          <div v-else-if="selectedTask.orderStatus === 2" >
            <div class="detail-item">
              <div class="orange">
                <div class="label">完成时间：</div>
              </div>
              <span class="value">{{ finishTime }}</span>
            </div>
            <div class="detail-item">
              <div class="orange-eva">
                <div class="label">评价：</div>
              </div>
              <div class="stars">
                <img v-for="n in 5" :key="n" :src="n <= selectedTask.rating ? fullStar : nullStar" class="star" /> <!-- 根据评价结果显示星星 -->
              </div>
            </div>
            <div v-if="activeFilter === '我领取的'" class="evaluate-span">
              <span>您已完成该订单</span>
            </div>
            <div v-else class="evaluate-btn">
              <button v-if="!selectedTask.rating" @click="showratingDialog">评价</button>
              <div v-else class="over">该订单已结束</div>
            </div>
          </div>
          
          
        </div>
      </div>
    </div>
  </div>

  <!-- 评价弹窗 -->
  <div v-if="showRating" class="rating-dialog-wrapper">
    <div class="rating-dialog-background" @click="showRating = false"></div>
    <div class="rating-dialog-content">
        <h3>评价订单</h3>
      <div class="stars">
        <img v-for="n in 5" :key="n" :src="n <= rating ? fullStar : nullStar" class="star" @click="setRating(n)" />
      </div>
      <button @click="submitRating">确认</button>
    </div>
  </div>
</template>
<script setup lang="ts">
import {ref,onMounted} from "vue"
import { useRouter } from "vue-router";
import { useTokenStore } from "../../stores/Login";
import { queryOrders,cancelOrder,completeOrder,completefinishOrder,deleteOrder,getfinishTime,evaluateOrder } from "../../api/Order/index";
import defaultAvatar from '../../assets/images/icon.png';
import nullStar from '../../assets/images/null-star.png';
import fullStar from '../../assets/images/full-star.png';

const finished = ref<boolean>(false);
const loading = ref<boolean>(false);
const orders = ref<Order[]>([]);
const page = ref<number>(1);
const size = ref<number>(10);
const searchText = ref('');
const activeFilter = ref('我发布的');
const maxPage = ref<number>(1);
const logined = ref<boolean>(true); // 登录状态
const showDialog = ref<boolean>(false);
const selectedTask = ref<Order | null>(null);
const finishTime = ref<string>('');
const showRating = ref<boolean>(false); // 控制评价弹窗显示
const rating = ref<number>(0); // 评价星级

const { user } = useTokenStore();
const router = useRouter();

// 时间格式化函数
const formatDate = (timestamp: string | number | Date) => {
  const date = new Date(timestamp);
  const year = date.getFullYear();
  const month = (date.getMonth() + 1).toString().padStart(2, '0');
  const day = date.getDate().toString().padStart(2, '0');
  const hour = date.getHours().toString().padStart(2, '0');
  const minute = date.getMinutes().toString().padStart(2, '0');
  const second = date.getSeconds().toString().padStart(2, '0');
  return `${year}-${month}-${day} ${hour}:${minute}:${second}`;
};

// 加载订单数据
const onLoad = async () => {
  if (page.value > maxPage.value) {
    finished.value = true;
    loading.value = false;
    return;
  }

  loading.value = true;

  const params = {
    page: page.value,
    size: size.value,
    userId: user.userId, // 从用户信息中获取用户 ID
    ordersType: activeFilter.value === '我发布的' ? 1 : (activeFilter.value === '我领取的' ? 2 : 0),
    filterString: searchText.value, // 搜索框的关键字
  };

  try {
    const response = await queryOrders(params);
    if (response.data.code === 200) {
      const fetchedOrders = response.data.data.orders.map((order: any) => ({
      ...order,
      rating: order.evaluate // 从 evaluate 获取评价星级
      }));
      if (page.value === 1) {
        orders.value = fetchedOrders; // 重置 orders 数组
      } else {
        orders.value = orders.value.concat(fetchedOrders);
      }
      page.value++;
      maxPage.value = response.data.data.totalPages;
    } else {
      finished.value = true;
    }
    loading.value = false;
  } catch (error) {
    console.log(error);
    loading.value = false;
  }
};

// 显示订单详情
const showOrderDetail = async (task: Order) => {
  selectedTask.value = task;
  showDialog.value = true;
  if (task.orderStatus === 2) {
    try {
      const response = await getfinishTime(task.orderId);
      finishTime.value = response.data.data;
    } catch (error) {
      console.error('获取订单完成时间失败:', error);
    }
  }
};

// 重置搜索
const onSearch = () => {
  page.value = 1; // 重置为第一页
  finished.value = false; // 重置结束状态
  loading.value = true; // 开始加载
  orders.value = []; // 清空当前订单
   onLoad(); // 执行加载
};

// 更新筛选条件
const setActiveFilter = (filter: string) => {
  activeFilter.value = filter;
  page.value = 1; // 重置页码为第一页
  finished.value = false; // 重置完成状态
  loading.value = true; // 开始加载数据
  orders.value = []; // 清空当前订单
  onLoad(); // 重新加载订单列表
};

// 取消订单
const cancelOrder1 = async () => {
  if (!selectedTask.value) return;
  try {
    await deleteOrder(selectedTask.value.orderId);
    console.log('取消订单成功:', selectedTask.value.orderId);
     // 更新本地存储的余额
    const refundAmount = selectedTask.value.reward; // 假设订单的奖励金额就是退款金额
    const storedUser = localStorage.getItem('user');
    if (storedUser) {
      const userData = JSON.parse(storedUser).user;
      userData.balance += refundAmount; // 增加余额
      localStorage.setItem('user', JSON.stringify({ user: userData }));
    }

    orders.value = orders.value.filter(order => order.orderId !== selectedTask.value.orderId); // 从订单列表中移除订单
    showDialog.value = false;
    onLoad(); // 重新加载订单列表
  } catch (error) {
    console.error('取消订单失败:', error);
  }
};

// 放弃订单
const abandonOrder = async () => {
  if (!selectedTask.value) return;
  try {
    await cancelOrder(selectedTask.value.orderId);
    selectedTask.value.orderStatus = 0; // 更新订单状态为空闲
    console.log('放弃订单成功:', selectedTask.value.orderId);
    orders.value = orders.value.filter(order => order.orderId !== selectedTask.value.orderId);
    showDialog.value = false;
    onLoad(); // 重新加载订单列表
  } catch (error) {
    console.error('放弃订单失败:', error);
  }
};

// 完成订单
const finishOrder = async () => {
  if (!selectedTask.value) return;
  try {
    await completeOrder(selectedTask.value.orderId);
    selectedTask.value.orderStatus = 3; // 更新订单状态为待确认
    console.log('订单转为待确认:', selectedTask.value.orderId);
    showDialog.value = false;
    onLoad(); // 重新加载订单列表
  } catch (error) {
    console.error('完成订单失败:', error);
  }
};

// 确认完成
const confirmCompletion = async () => {
  if (!selectedTask.value) return;
  try {
    await completefinishOrder(selectedTask.value.orderId);
    selectedTask.value.orderStatus = 2; // 更新订单状态为已完成
    console.log('确认完成成功:', selectedTask.value.orderId);
    showDialog.value = false;
    onLoad(); // 重新加载订单列表
  } catch (error) {
    console.error('确认完成失败:', error);
  }
};

// 提交评价
const submitRating = async () => {
  if (!selectedTask.value) return;
  try {
    const response = await evaluateOrder(selectedTask.value.orderId, rating.value);
    console.log('评价成功:', response.data);
    selectedTask.value.rating = rating.value; // 更新评价结果
    showRating.value = false;
  } catch (error) {
    console.error('评价失败:', error);
  }
};


// 显示评价弹窗
const showratingDialog = () => {
  showRating.value = true;
};

// 设置评价星级
const setRating = (stars: number) => {
  rating.value = stars;
};

// 订单数据类型
interface Order {
  orderId: number;
  status: number;
  pickupAddress: string;
  deliveryAddress: string;
  reward: number;
  timeAgo: string;
  isPublishedByUser: boolean;
  orderStatus:number; // 是否由用户发布
  completionTime: string; // 添加订单完成时间属性
  rating: number; // 添加评价属性
}

// 判断是否登录
onMounted(()=>{
  user.token ? logined.value=true : logined.value=false
})

// 跳转到登录界面
const gotologin =() =>{
  router.push('/login')
}

  
</script>
<style lang="less" scoped>
.status-dot {
  display: inline-block;
  width: 12px; /* 圆点宽度 */
  height: 12px; /* 圆点高度 */
  border-radius: 50%; /* 圆点边框半径，50% 表示圆形 */
  margin-top: 15px; 
}

/* 定义不同状态的圆点颜色 */
.status-ongoing .status-dot {
  background-color: #9A9A9A; /* 空闲中的圆点颜色 */
}

.status-ongoing  {
  color: #9A9A9A; 
}

.status-completed .status-dot {
  background-color: #07c160; /* 进行中的圆点颜色 */
}

.status-completed  {
  color: #07c160; 
}

.status-pending .status-dot {
  background-color: #FF8C00; /* 进行中的圆点颜色 */
}

.status-pending  {
  color: #FF8C00; 
}

.status-done .status-dot {
  background-color: #FD5958; /* 进行中的圆点颜色 */
}

.status-done  {
  color: #FD5958; 
}

.order-hall {
  background-color: #f7f8fa;
  min-height: 100vh;
}
.task-hall {
  background-color: #f7f8fa; /* 背景颜色 */
  min-height: 100vh; /* 最小高度设为视口高度 */
}

.yellow-tag {
  background-color: #ffcc00; /* 黄色背景 */
  color: #a75910; 
}
.green-tag {
  background-color: #76e06f; /* 绿色背景 */
  color: #188302; 
}
.search-container {
  padding: 8px 16px; /* 内间距 */
  background-color: #ffffff; /* 背景颜色 */
  display: flex; /* 采用 flex 布局 */
  align-items: center; /* 垂直居中 */
  gap: 8px; /* 子元素之间距离 */
}

.search-button {
  border-radius: 100px; /* 按钮圆角 */
  background-color: #ff6b6b; /* 背景颜色 */
  border-color: #ff6b6b; /* 边框颜色 */
  flex-shrink: 0; /* 不允许收缩 */
}

.filter-buttons {
  background-color: #ffffff; /* 背景颜色 */
  display: flex; /* flex 布局 */
  padding: 12px 16px; /* 内间距 */
  justify-content: space-evenly; /* 等间距分布 */
  gap: 12px; /* 按钮间距 */
}

.filter-button {

  flex: 1; /* 让按钮自动扩展并填充容器 */
  margin: 0 10px; /* 按钮之间增加间距 */
  padding: 0 20px; /* 增加内边距使按钮更长 */
  min-width: 100px; /* 设置按钮的最小宽度 */
  border-radius: 100px; /* 按钮圆角 */
  font-size: 14px; /* 字体大小 */
  border-color: #e8e8e800; /* 边框颜色，透明 */
  color: #323233; /* 字体颜色 */
}

.filter-button.active {
  color: #ff6b6b; /* 活动状态文本颜色 */
  background-color: #ffefef; /* 背景颜色 */
  border-color: #fdfdfd00; /* 边框颜色 */
}
.orderList{
    margin: 10px;
}

.description {
  font-weight: bold; /* 字体加粗 */
  color: #000;
  text-align: left;
  display: block;
  margin-left: 10px;
}
.item{
    text-align: left;
    display: block;
    margin-left: 20px;
}
.logoStyle{
    width: 20px;
    height: 20px; 
    margin-right: 5px;
}

.addressStyle{
    font-size: 14px;
    font-weight: bold;
    color: #000000;
    text-align: left;
    display: block;
    margin-left: 10px;

}
.task-price {
  text-align: right; /* 右对齐 */
}

/* 去除每个 van-cell 的底部边框 */
.van-cell:after {
  border-bottom: none !important;
}
.price {
  color: #ff6b6b; /* 价格文本颜色 */
  font-weight: bold; /* 加粗 */
  font-size: 16px; /* 字体大小 */
}

.order-info {
  font-weight: bold;
  color: #000;
  text-align: left;
  display: block;
  margin-left: 10px;
  margin-top: 9px;
}

/* Vant 组件的样式自定义 */
:deep(.van-nav-bar__title) {
  color: #ff6b6b; /* 标题颜色 */
}

:deep(.van-search__action) {
  padding: 0 8px; /* 搜索框动作按钮内边距 */
}

:deep(.van-badge--dot) {
  top: 0; /* 上边距 */
  right: 0; /* 右边距 */
}

:deep(.van-search) {
  padding: 0; /* 搜索框内边距 */
}

.unlogin {
  width: 223px;
  height: 255px;
  position: absolute;
  left: 50%;
  transform: translateX(-50%);
  top: 30%;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  text-align: center;
}

.unlogin img{
  width: 125px;
  margin-bottom: 15px;
}

.unlogin .des{
  font-size: 15px;
  color: #6C6C6C;
  margin-top: 10px;
  margin-bottom: 20px
}

.unlogin button{
  width: 129px;
  height: 48px;
  background-color: rgba(252, 30, 9, 0.8);
  color: #FFFFFF;
  border: none;
  border-radius: 4px;
}

.dialog-wrapper {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.dialog-background {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5); /* 半透明黑色背景 */
}

.dialog-content {
  position:absolute;
  top: 65px;
  left: 10px;
  background-color: #fff;
  padding: 20px;
  border-radius: 10px;
  z-index: 1001;
  width: 80%;
  max-width: 400px;
  height: 363px;
}

.dialog-content-large{
  height: 450px;
}

.order-detail {
  margin-top: 10px;
}

.detail-item {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;
  align-items: center;
}


.label {
  font-weight: bold;
  color: #FFFFFF;
  margin-left: 15px;
  margin-top: 5px;
}

.value {
  width: 128px;
  color: #333;
}

.content-background{
  position: relative;
  width: 300px;
  height: 417px;
  background-color: #FFBF6B;
  border-radius: 40px 16px 16px 16px;
  padding-top: 65px;
}

.content-background-large {
  height: 505px; /* 调整高度 */
}

.content-background h3{
  color: #D37902;
  font-size: 24px;
  width: 100px;
  position:absolute;
  top: 20px;
  left: 40px;
}

.back-person{
  width: 183px;
  height: 119px;
  position: absolute;
  top: -40px;
  left: 160px;
}

.self-order {
  color: #f56c6c;
  font-weight: bold;
  margin-left: 40px;
  margin-top: 10px;
}

.orange{
  width: 100px;
  height: 30px;
  background: #FFCB87;
  border-radius: 10px;
}

.orange-eva{
  width: 100px;
  height: 30px;
  background: #FFCB87;
  border-radius: 10px;
  text-align: center;
}

.orange-qu{
  width: 100px;
  height: 30px;
  background: #FFCB87;
  border-radius: 10px;
  text-align: center;
}

.cancel-btn{
  text-align: center;
  
}
.cancel-btn button{
  width: 100px;
  height: 35px;
  background: #FF6B6B;
  border-radius: 4px;
  border: none;
  color: #fff;
}

.orderisdoing{
  text-align: center;
}
.orderisdoing span{
  color: #FF6B6B;
  font-weight: bold;
}
.doing-span{
  margin-top: 30px;
}

.doing-btn{
  text-align: center;
}
.doing-btn button{
  width: 100px;
  height: 35px;
  border-radius: 4px;
  border: none;
  color: #fff;
}
.doing-btn button.btn1{
  margin-right: 10px;
  background: #FF6B6B;
}
.doing-btn button.btn2{
  background: #4095E5;
}

.confirm-btn{
  text-align: center;
}
.confirm-btn button{
  width: 100px;
  height: 35px;
  background: #4095E5;
  border-radius: 4px;
  border: none;
  color: #fff;
}
.confirm-btn span{
  color: #FF6B6B;
  font-weight: bold;
  
}
.confirm-span{
  margin-top: 30px;
}
.evaluate-span{
  text-align: center;
  margin-top: 30px;
}
.evaluate-span span{
  color: #FF6B6B;
  font-weight: bold;
  
}

.evaluate-btn{
  text-align: center;
}
.evaluate-btn button{
  width: 100px;
  height: 35px;
  background: #FF6B6B;
  border-radius: 4px;
  border: none;
  color: #fff;
}
.evaluate-btn .over{
  color: #FF6B6B;
  font-weight: bold;
  margin-top: 30px;
}

.star{
  width: 20px;
  height: 20px;
  margin-right: 2px;
}

.rating-dialog-wrapper {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.rating-dialog-background {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5); /* 半透明黑色背景 */
}

.rating-dialog-content {
  position: relative;
  width: 300px;
  background-color: #fff;
  border-radius: 10px;
  padding: 20px;
  z-index: 1001;
  text-align: center;
}

.rating-dialog-wrapper h3{
  color: #FF8C00;
  font-size: 24px;
  margin-bottom: 10px;
}

.rating-dialog-wrapper button{
  width: 100px;
  height: 35px;
  background: #FF6B6B;
  border-radius: 4px;
  border: none;
  color: #fff;
  margin-top:10px;
}
</style>
